package com.zxjbyte.yiyi.framework.tenant.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.zxjbyte.yiyi.framework.mybatis.util.MybatisUtil;
import com.zxjbyte.yiyi.framework.tenant.aspect.YiyiTenantAspect;
import com.zxjbyte.yiyi.framework.tenant.db.handler.YiyiTenantHandler;
import com.zxjbyte.yiyi.framework.tenant.redis.TenantRedisKeyDefine;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

/**
 * 多租户配置类
 * @Author zhangxingjia
 * @Date 2023/3/14 18:38
 * @Version: 1.0
 */
@AutoConfiguration
@ConditionalOnProperty(prefix = TenantProperties.TENANT_PROP_PREFIX, value = "enabled", matchIfMissing = true) // 允许使用 yiyi.tenant.enable=false 禁用多租户
@EnableConfigurationProperties(TenantProperties.class)
public class YiyiTenantAutoConfiguration {


    // ===============DB================
    @Bean
    public YiyiTenantHandler yiyiTenantHandler(TenantProperties properties){
        return new YiyiTenantHandler(properties);
    }

    @Bean
    @Primary
    public TenantLineInnerInterceptor tenantLineInnerInterceptor(YiyiTenantHandler tenantHandler, MybatisPlusInterceptor mybatisPlusInterceptor) {
        TenantLineInnerInterceptor tenantLineInnerInterceptor = new TenantLineInnerInterceptor(tenantHandler);
        // 需要加在首个，主要是为了在分页插件前面。这个是 MyBatis Plus 的规定
        MybatisUtil.addInterceptor(mybatisPlusInterceptor, tenantLineInnerInterceptor, 0);
        return tenantLineInnerInterceptor;
    }

    @Bean
    public YiyiTenantAspect yiyiTenantAspect() {
        return new YiyiTenantAspect();
    }

    @Bean
    public TenantRedisKeyDefine tenantRedisKeyDefine(TenantProperties properties){
        return new TenantRedisKeyDefine(properties);
    }

}
